import heapq
class STvalue():
    def __init__(self, t, val):
        self.t = t
        self.val = val

def dijkstra(grid, N, start):
    min_dist = [float('inf')] * (N+1)
    visited = [False] * (N+1)
    hq = []
    
    heapq.heappush(hq, (0, 1))
    while hq:
        min_data, cur = heapq.heappop(hq)
        if visited[cur]:
            continue
        
        visited[cur] = True
        
        for st_value in grid[cur]:
            t = st_value.t
            value = st_value.val
            if not visited[t] and value+min_data < min_dist[t]:
                min_dist[t] = value+min_data
                heapq.heappush(hq, (min_dist[t], t))
    
    return min_dist 
    

def main():
    N, M = map(int, input().split())
    
    grid = [[] for _ in range(N+1)]
    
    for i in range(M):
        s, t, value = map(int, input().split())
        grid[s].append(STvalue(t, value))

    
    min_dist = dijkstra(grid, N, 1)
    if min_dist[-1] == float('inf'):
        print(-1)
    else:
        print(min_dist[-1])
    return

main()